package store.wetravel.web.backend.category.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import store.wetravel.common.ServerResponse;
import store.wetravel.pojo.Category;
import store.wetravel.web.backend.category.mapper.CategoryMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * Created by xinlong on 2017/10/25.
 */
@Service("iCategoryService")
public class CategoryServiceImpl implements ICategoryService {


    private Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Resource(name="categoryMapper")
    private CategoryMapper categoryMapper;

    public ServerResponse addCategory(String categoryName, Integer parentId){
        if(parentId == null || StringUtils.isBlank(categoryName)){
            return ServerResponse.createByErrorMessage("添加商品类参数错误");
        }

        Category category = new Category();
        category.setName(categoryName);
        category.setParentId(parentId);
        category.setStatus(true);   //这个分类是可用的

        int rowCount = categoryMapper.insert(category);
        if(rowCount > 0 ){
            return ServerResponse.createBySuccessMessage("添加品类成功");
        }
        return ServerResponse.createByErrorMessage("添加品类失败");
    }

    public ServerResponse updateCategoryName(Integer categoryId,String categoryName){
        if(categoryId == null || StringUtils.isBlank(categoryName)){
            return ServerResponse.createByErrorMessage("更新商品累参数错误");
        }
        Category category = new Category();
        category.setId(categoryId);
        category.setName(categoryName);

        int rowCount = categoryMapper.updateByPrimaryKeySelective(category);
        if(rowCount > 0){
            return ServerResponse.createBySuccess("更新品类名字成功");
        }
        return ServerResponse.createByErrorMessage("更新品类名失败");
    }

    /**
     * 递归删除分类节点
     * @param categoryId
     * @return
     */
    public ServerResponse deleteCategory(Integer categoryId){
        if(categoryId == null || categoryId<=0){
            return ServerResponse.createByErrorMessage("删除商品类参数错误");
        }
        deleteChildCategory(categoryId);
        return ServerResponse.createBySuccess();
    }

    //递归算法，算出并删除子节点
    private void deleteChildCategory(Integer categoryId){
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if(category != null){
            //查找子节点，递归算法一定要有一个退出的条件
            List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
            for(Category categoryItem :categoryList){
                deleteChildCategory(categoryItem.getId());
            }
            //递归完删除本节点
            categoryMapper.deleteByPrimaryKey(categoryId);
        }
    }

    /**
     * 查询当前分类
     */
    public ServerResponse<Category> selectCategoryById(Integer categoryId){
        if(categoryId == null || categoryId<0){
            return ServerResponse.createByErrorMessage("查询分类参数错误");
        }
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if(category==null){
            return ServerResponse.createByErrorMessage("无此分类");
        }
        return ServerResponse.createBySuccess(category);
    }
    /**
     * 查询子分类（不递归）
     * @param categoryId
     * @return
     */
    public ServerResponse<List<Category>> getChildrenParallelCategory(Integer categoryId){
        List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
        if(CollectionUtils.isEmpty(categoryList)){
            logger.info("未找到当前分类的子分类");
        }
        return ServerResponse.createBySuccess(categoryList);
    }

    /**
     * 递归查询本节点的id及父亲节点的id
     * @param categoryId
     * @return
     */
    public ServerResponse<List<Category>> selectCategoryAndParentById(Integer categoryId){
        Set<Category> categorySet = Sets.newTreeSet();
        findParentCategory(categorySet,categoryId);

        List<Category> categoryIdList = Lists.newArrayList();
        if(categoryId != null){
            for(Category categoryItem:categorySet){
                categoryIdList.add(categoryItem);
            }
        }
        return ServerResponse.createBySuccess(categoryIdList);
    }

    //递归算法，算出父节点
    private Set<Category> findParentCategory(Set<Category> categorySet,Integer categoryId){
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if(category != null){
            categorySet.add(category);
        }
        //查找父节点，递归算法一定要有一个退出的条件
        //此处0为地区的根节点，1为属性的根节点
        if(categoryId == 0||categoryId == 1){
            return categorySet;
        }
        findParentCategory(categorySet,category.getParentId());
        return categorySet;
    }


    /**
     * 递归查询本节点的id及孩子节点的id
     * @param categoryId
     * @return
     */
    public ServerResponse<List<Integer>> selectCategoryAndChildrenById(Integer categoryId){
        Set<Category> categorySet = Sets.newHashSet();
        findChindCategory(categorySet,categoryId);

        List<Integer> categoryIdList = Lists.newArrayList();
        if(categoryId != null){
            for(Category categoryItem:categorySet){
                categoryIdList.add(categoryItem.getId());
            }
        }
        return ServerResponse.createBySuccess(categoryIdList);
    }

    //递归算法，算出子节点
    private Set<Category> findChindCategory(Set<Category> categorySet,Integer categoryId){
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if(category != null){
            categorySet.add(category);
        }
        //查找子节点，递归算法一定要有一个退出的条件
        List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
        for(Category categoryItem :categoryList){
            findChindCategory(categorySet,categoryItem.getId());
        }
        return categorySet;
    }

}
